<template>
  <div class="pre-archive-detail">
    <el-dialog
      width="70%"
      class="WholeScroll"
      :visible.sync="formShow"
      @close="handleClickDeal('cancel')"
      v-dialog-drag
      :modal-append-to-body="false"
      :close-on-click-modal="false"
    >
      <span slot="title">
        <i class="iconfont icon-shuju"></i>
        <span>{{ title }}</span>
      </span>

      <div class="WholeScroll" style="max-height: 650px; overflow: auto;padding: 0 15px;">
        <el-form
          :model="formBaseData"
          ref="formBaseData"
          :rules="formBaseRules"
          style="position: relative"
          v-if="activeName == 'first'"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="名称" prop="name" :label-width="formlabelWidth">
                <el-input :disabled="detailType !== 'build' && detailType !== 'edit'" class="contract-ele" v-model="formBaseData.name" placeholder="请输入名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属项目" prop="project" :label-width="formlabelWidth">
                <el-select
                  class="select" style="width: 100%" value-key="id" v-model="formBaseData.projectId" placeholder="请选择所属项目" clearable
                  :disabled="detailType === 'check' || !canEdit" required>
                  <el-option
                    v-for="item in selectList.projectList" :key="item.projectId" :label="item.label" :value="item.projectId">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="路由地址" prop="route" :label-width="formlabelWidth">
                <el-input class="contract-ele" v-model="formBaseData.route" placeholder="请输入地址"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="录入人" prop="creater" :label-width="formlabelWidth">
                <el-input disabled class="contract-ele" v-model="formBaseData.creater" placeholder="录入人"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="录入时间" prop="createTime" :label-width="formlabelWidth">
                <el-input disabled class="contract-ele" v-model="formBaseData.createTime" placeholder="录入时间"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <template v-if="detailType === 'build' || detailType === 'edit'">
          <el-button size="small" type="primary" :loading="isLoading" @click="handleClickDeal('submit', { flag: 1 })">
            <i class="iconfont icon-icon_save"></i> 确 定
          </el-button>
        </template>
        <el-button size="small" @click="handleClickDeal('cancel')">
          <i class="iconfont icon-icon_cancel"></i> 取 消
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import projectEntrance from "@/api/buss/projectEntrance";

export default {
  name: 'temporary-deposit-detail',
  components: {},
  props: {
    postDetail: {
      type: Object,
      default: {
        show: false,
        type: 'build',
        params: {}
      }
    }
  },
  watch: {
    postDetail(value) {
      // 显示详情弹窗
      this.formShow = value.show
      // 初始化窗口参数
      this.activeName = 'first'
      // 详情类型
      this.detailType = value.type
      this.companyTree = [];
      this.projectTree = [];
      this.contsectTree = [];
      this.measurePhase = [];

      if (this.detailType == 'build') {
        this.title = '新增'
        this.getCreaterInfo()
      } else if (this.detailType == 'check') {
        this.title = '查看详情'
        this.getCreaterInfo()
      } else if (this.detailType == 'edit') {
        this.title = '编辑'
      } else {
        this.title = ''
      }

      // 详情的流程操作处理
      this.detailActions.splice(0, this.detailActions.length)
      if (value.params) {
        for (let key in value.params.actions) {
          if (key !== 'show' && key !== 'update' && key !== 'getHistory') {
            this.$set(this.detailActions, this.detailActions.length, {
              name: value.params.actions[key].name,
              url: value.params.actions[key].url,
              key: key
            })
          }
        }
      }
      // 详情id
      this.detailId = value.params === undefined ? 0 : value.params.detailId
      this.getProjectList()
      if (this.detailType !== 'build') {
        this.getDetail()
      }else{
      }


    }
  },
  data() {
    return {
      companyTree:[],
      projectTree:[],
      contsectTree:[],
      measurePhase:[],
      isLoading: false,
      detailType: 'build', // 详情类型 build新建 check不可编辑查看 edit编辑
      detailId: '', // 当前详情的id
      detailActions: [], // 当前详情的操作项
      formShow: false, // 表单展示
      formlabelWidth: '130px', // 表单左侧标题宽度
      title: '',
      activeName: 'first',
      buildUnitTable: [
        {
          stuffName: '附件',
          part: 'partOne',
          file: [{ realName: '' }],
          isNeed: false,
          loading: false,
          isMulti: true
        }
      ],
      fileSystem: {
        attachId: {
          partOne: '',
          partTwo: '',
          partThree: '',
          partFour: '',
          other: '',
          taohong: ''
        },
        sys: 'buss',
        module: 'smartWorkSite',
        entityClass: 'smartWorkSite',
        viewByAnon: true,
        longLife: false,
        part: {
          partOne: 'partOne',
          partTwo: 'partTwo',
          partThree: 'partThree',
          partFour: 'partFour',
          other: 'other'
        }
      },
      selectList: {
        projectList: [],
        companyList: [],
        //
        propertiesFieldOptions: [
          {
            label: '属性',
            value: ''
          }
        ],
        //
        file: []
      }, // 所有下拉框列表的集合
      formBaseData: {
        name: "",
        projectId: "",
        route: "",
        creater: "",
        createTime: new Date().Format("yyyy-MM-dd HH:mm:ss")
      }, // 表单基本信息内容

      formBaseRules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'change'}
        ],
        projectId: [
          { required: true, message: '请选择项目', trigger: 'change'}
        ],
      }, // 表单基本信息验证
      canEdit: true,
    }
  },


  methods: {
    /**
     * 修正查询参数并查询
     *
     * */
    fixQueryA() {
      if (this.formBaseData.company.children && this.formBaseData.company.children.length) {
        this.formBaseData.project = this.formBaseData.company.children[0]
      } else {
        this.formBaseData.project = {}
      }
      this.fixQueryB()
    },
    fixQueryB() {
      if (this.formBaseData.project.children && this.formBaseData.project.children.length) {
        this.formBaseData.section = this.formBaseData.project.children[0]
      } else {
        this.formBaseData.section = {}
      }
      this.fixQueryC()
    },
    fixQueryC() {
      if (this.formBaseData.section.children && this.formBaseData.section.children.length) {
        this.formBaseData.measurePhaseId = this.formBaseData.section.children[0].id
      } else {
        this.formBaseData.measurePhaseId = ''
      }
    },
    blurInputEvent(value){
      if(value){
        value.target.value = Number(value.target.value).toFixed(2)
      }
    },

    getCreaterInfo(){
      this.$httpGet(
        `/buss/smartWorkSite/getCreaterInfo`,
        {}
      ).then(res => {
        if (res.code === 200) {
          this.formBaseData.creater = res.data.creater;
          this.formBaseData.createTime = res.data.createTime;
        } else {
          this.$messageError(res.msg)
          return false
        }
      })
    },
    getProjectList() {
      this.$httpGet(
        `/buss/smartWorkSite/getProjectList`,
        {}
      ).then(res => {
        if (res.code === 200) {
          this.selectList.projectList = res.data.map(e => {
            return { label: e.proName, projectId: e.projectId, value: `${e.proName}|${e.projectId}` }
          })
        } else {
          this.$messageError(res.msg)
          return false
        }
      })
    },

    // 获取详情请求 api
    getDetail() {
      this.$httpGet(
        `/buss/smartWorkSite/getOne?id=${this.detailId}`,
        {}
      ).then(async (res) => {
          if (res.code === 200) {
            this.formBaseData = res.data
            this.$forceUpdate()

          } else {
            this.$messageError(res.msg)
          }
        })
        .catch((res) => {
          console.log('请求出现错误', res)
          this.$messageError(this.$route.name + '获取详情请求-请求失败')
        })
    },

    // 提交详情 提交1/暂存0 新建0/修改1
    submitDetail(type, callback) {
      let submit = '/buss/smartWorkSite/add'
      if (this.detailType === 'build') {
        submit = '/buss/smartWorkSite/add'
      } else {
        submit = '/buss/smartWorkSite/resubmit'
      }
      this.$httpPost(
        submit,
        this.formBaseData
      ).then((res) => {
          if (res.code === 200) {
            this.$messageSuccess('保存成功')
            this.detailId = !this.detailId ? res.data.id : this.detailId
            this.isLoading = false
            if (callback) callback()
          } else {
            this.isLoading = false
            if(res.msg){
              this.$messageError(res.message)
            }else {
              this.$messageError(this.$route.name + '提交详情-请求失败')
            }          }
        }).catch((res) => {
          console.log('请求出现错误', res)
          this.isLoading = false
          if(res.msg){
            this.$messageError(res.message)
          }else {
            this.$messageError(this.$route.name + '提交详情-请求失败')
          }          })
    },
    // 事件处理的api请求
    sealDealHttp(url, query, params, callback) {
      this.$httpPost( url + query, params)
        .then((res) => {
          if (res.data.status === 1) {
            if (callback) callback(res.data)
          } else {
            this.$messageError(res.data.message)
          }
        })
        .catch((res) => {
          console.log('请求出现错误', res)
          console.log(res)
        })
    },
    // 点击各个流程的按钮事件
    handleClickDeal(type, res) {
      switch (type) {
        // 取消，关闭窗口
        case 'cancel':
          // 重置表单验证
          console.log(this.activeName)
          this.$refs['formBaseData'].resetFields()
          this.formBaseData= {
            name:"",
            projectId: "",
            route: "",
            creater: "",
            createTime: "",
          }
          // 清空文件
          // 关闭弹窗
          this.formShow = false
          break
        // 保存
        case 'submit':
          let flag = res.flag
          // 表单验证
          this.$refs['formBaseData'].validate((valid) => {
            if (valid) {
              // 再验证其他内容
              // 整理文件信息
              this.isLoading = true
              // 提交详情
              this.submitDetail(flag, () => {
                this.formShow = false
                this.isLoading = false
                // 传值给父组件刷新列表
                this.$emit('reloadList')
                this.$bus.$emit('Ajax')
              })
            } else {
              this.isLoading = false
            }
          })
          break
        // 删除
        case 'delete':
          this.$prompt('删除理由', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消'
          })
            .then(({ value }) => {
              if (value === null || value === '') {
                this.$messageError('请填写删除理由后重试')
                return
              }
              this.sealDealHttp(
                res.url,
                ``,
                {
                  id: this.detailId,
                  description: value
                },
                () => {
                  this.$messageSuccess('删除成功!')
                  this.formShow = false
                  // 传值给父组件刷新列表
                  this.$emit('reloadList')
                  this.$bus.$emit('Ajax')
                }
              )
            })
            .catch(() => {})
          console.log('请求出现错误')
          break
      }
    },

    tableChange(val) {
      this.$set(this, 'buildUnitTable', [...val])
    },
    // 点击单元格
    cellClick(row, column, cell, event) {
      // console.log(row, column, cell, event)
      console.log(column)
      if (column.property === 'projectName') {
        this.handleClickDeal({
          type: 'show',
          detailId: row.id,
          actions: row.actions
        })
      }
    }
  }
}
</script>

<style scoped lang="scss">
.contract-ele {
  width: 100%;
}
.contract-ele-long {
  //   width: 280px;
  width: 98%;
}

.el-input .el-select {
  width: 130px;
}

.formTitle {
  font-weight: bold;
  font-size: 16px;
}

.hoverTxt {
  color: #008fe0;
  cursor: pointer;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
